const express = require('express');
var router = express.Router();
const writeSQL = require('../js/writeSQL');
const jwt = require('jsonwebtoken');

// 这是一个示例密钥，实际情况中应该更安全地存储密钥
const secretKey = 'my_secret_key';
// 模拟一个生成令牌的函数
function generateToken(user) {
    return jwt.sign(user, secretKey);
}

router.post('/login', (req, res) => {
    writeSQL('select * from users where user_name = ? and password = ?', [req.body.username, req.body.password]).then(result => {
        if (result[0]) {
            const token = generateToken(result[0].userName);
            // 返回成功响应
            res.status(200).json({
                msg: '登录成功',
                data: {
                    ...result[0],
                    token
                }
            });
        }else{
            res.status(400).json({
                msg: '用户名或密码错误'
            });
        }
        
    }).catch((err)=>{
        res.status(500).json({
                msg: err
            });
    });
});

router.post('/register', (req, res) => {
    writeSQL('INSERT INTO users (user_name, password) VALUES (?, ?);', [req.body.username, req.body.password]).then(result => {
        console.log(result);
        res.status(200).json({
            msg: '注册成功'
        });
        
    }).catch((err)=>{
        res.status(500).json({
                msg: err
            });
    });
});

module.exports = router;